<template>
  <div class="myContainer">
    <el-row class="myTitleBorderBottom myMarginBottom_10px">
      <el-col :span="12" class="myLineHeight_40px">
        <span v-if="type=='add'">新增</span>
        <span v-if="type=='update'">编辑</span>
        <span v-if="type=='info'">详情</span>
      </el-col>
    </el-row>
    <el-row class="myPaddingBottom_10px">
      <el-col :span="3" class="myLeftMsg">
        <span class="require myVA_M">*</span>
         标题:
      </el-col>
      <el-col :span="7">
        <el-input placeholder="请输入标题" v-model="newsTitle" :readonly="is_modifly"></el-input>
      </el-col>
    </el-row>
    <el-row class="myPaddingBottom_10px">
      <el-col :span="3" class="myLeftMsg">
        <span class="require myVA_M">*</span>
         概要:
      </el-col>
      <el-col :span="14">
        <el-input placeholder="请输入概要" v-model="newsDigest" :readonly="is_modifly"></el-input>
      </el-col>
    </el-row>
    <el-row class="myPaddingBottom_10px">
      <el-col :span="3" class="myLeftMsg">
        <span class="require myVA_M">*</span>
         发布时间:
      </el-col>
      <el-col :span="7">
        <el-date-picker
          v-model="time"
          type="datetime"
          format="yyyy-MM-dd HH:mm"
          value-format="yyyy-MM-dd HH:mm"
          placeholder="发布时间">
        </el-date-picker>
      </el-col>
    </el-row>
    <el-row class="myPaddingBottom_10px" :gutter="10">
      <el-col :span="3" class="myLeftMsg">
        <span class="require myVA_M">*</span>
         发布范围:
      </el-col>
      <el-col :span="4">
        <el-select 
          v-model="userTypeScope"
          @change="clickUserTypeScopeChange"
          placeholder="请选择发布范围">
          <el-option
            v-for="item in Object.keys(publishUserTypeScope)"
              :key="publishUserTypeScope[item]"
              :label="publishUserTypeScope[item]"
              :value="item">
          </el-option>
        </el-select>
      </el-col>

      <el-col :span="4">
        <el-select 
          v-model="range"
          @visible-change="clickRange"
          placeholder="请选择发布部门/小区">
          <el-option
            v-for="item in rangeList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-col>
    </el-row>
    <el-row class="myPaddingBottom_10px">
      <el-col :span="3" class="myLeftMsg">
         <span class="require myVA_M">*</span>
         类型:
      </el-col>
      <el-col :span="7" class="myLineHeight_40px">
        <template>
          <el-radio-group v-model="articleType">
            <el-radio :label="2">通知</el-radio>
            <el-radio :label="3">公告</el-radio>
          </el-radio-group>
        </template>
      </el-col>
    </el-row>
    <el-row class="myPaddingBottom_10px">
      <el-col :span="3" class="myLeftMsg">
         发布者标签:
      </el-col>
      <el-col :span="7">
        <el-input placeholder="请输入发布者标签" v-model="publishName" :readonly="is_modifly"></el-input>
      </el-col>
    </el-row>
    <el-row class="myPaddingBottom_10px">
      <el-col :span="3" class="myLeftMsg">
        <span class="require myVA_M">*</span>
         状态:
      </el-col>
      <el-col :span="7" class="myLineHeight_40px">
        <template>
          <el-radio-group v-model="newsStatus">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">停用</el-radio>
          </el-radio-group>
        </template>
      </el-col>
    </el-row>
    <el-row class="myTitleBorderBottom myMarginBottom_10px">
      <el-col :span="12" class="myLineHeight_40px">
        封面图片及正文信息
      </el-col>
    </el-row>
    <el-row class="myPaddingBottom_10px">
      <el-col :span="3" class="myLeftMsg">
         封面缩略图:
      </el-col>
      <el-col :span="7">
        <el-upload
          class="avatar-uploader"
          :action="uploadUrl"
          :show-file-list="false"
          :before-upload="beforeAvatarUpload"
          :data="postData"
          :on-success="handleAvatarSuccess">
          <img v-if="thumbnailUrl" :src="thumbnailUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
        <span style="color: #f00">上传图片尺寸比例15:11,建议图片大小为100KB,格式为JPG/PNG。</span>
      </el-col>
    </el-row>
     <el-row class="myPaddingBottom_10px">
      <el-col :span="3" class="myLeftMsg">
         外部链接:
      </el-col>
      <el-col :span="14">
        <el-input placeholder="新闻外部链接（正文不需要再添加）" v-model="extraUrl" :readonly="is_modifly"></el-input>
      </el-col>
    </el-row>
    <el-row class="myPaddingBottom_10px">
      <el-col :span="3" class="myLeftMsg">
         正文:
      </el-col>
      <el-col :span="17">
        <quill-editor
            v-model="content"
            ref="myQuillEditor"  
            :options = "editorOption"  
            @change="onEditorChange($event)">
        </quill-editor> 
        <!-- 文件上传input 将它隐藏-->
        <el-upload 
          :action="qnLocation" 
          :before-upload='beforeUpload' 
          :data="postData" 
          :on-success='upScuccess'
          ref="upload" 
          style="display:none">
          <el-button 
            size="small" 
            type="primary" 
            id="imgInput" 
            element-loading-text="插入中,请稍候">
            点击上传
          </el-button>
        </el-upload>
      </el-col>
    </el-row>
    <el-row class="myPaddingBottom_10px">
      <el-col :span="7" :offset="3">
        <el-button type="primary" class="myBgGreen" v-if="type=='update'||type=='add'" @click="onPreview">预 览</el-button>
        <el-button type="primary" class="myBgGreen" v-if="type=='update' && isShow(138)" @click="modify">保 存</el-button>
        <el-button type="primary" class="myBgGreen" v-if="type=='add'" @click="create">新 增</el-button>
        <el-button type="primary" class="myBgGreen" @click="back">返 回</el-button>
      </el-col>
    </el-row>

    <el-dialog title="预览" class="myIframe" :visible.sync="onPreviewDialog" @open="onOpen">
      <iframe id="myIframe" style="width: 414px; height: 700px; border:1px solid #f5f5f5; background: none"></iframe>
    </el-dialog>
  </div>
</template>
<style scoped>
  .myContainer{
    background: #fff;
    padding: 10px;
  }
  .myTitleBorderBottom{
    color: #000;
    font-weight: 500;
    font-size: 16px;
    border-bottom: 1px solid #dbdbdb;
  }
  .myBgGreen{
    background: #00c2a9;
    border-color: #00c2a9;
    color: #fff;
    margin-top:2px;
  }
  .myBgGreen:hover{
    background: #33ceba;
  }
  .myTextAlignRight{
    text-align: right;
  }
  .myLineHeight_40px{
    line-height: 40px;
  }
  .myMarginTop_10px{
    margin-top: 10px;
  }
  .myLeftMsg{
    line-height: 40px;
    text-align: right;
    padding-right: 10px;
  }
  .myPaddingBottom_10px{
    padding-bottom: 10px;
  }
  .myVA_M{
    vertical-align: middle;
  }
  .myMarginBottom_10px{
    margin-bottom: 20px;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
    border:1px solid #d8dce5;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
<script>
  import { quillEditor } from 'vue-quill-editor';
  import { QINIU_API , QINIU_UP_API } from '@/config/baseUrl';
  import { getArticleDetail, modifyArticle, addArticle,
          publishUserTypeScope, getQNToken } from '@/api/contentMGT';
  import { getAreaList } from '@/api/area';       
  export default {
    data(){
      return{
       title: "通知公告管理",
        id: "",
        type:"",
        is_modifly:false,

        newsDigest:"",
        time:"",
        extraUrl:"",

        newsStatus:1,
        uploadUrl:QINIU_UP_API,
        thumbnailUrl:"",
        postData:{
          token:""
        },
        onPreviewDialog:false,
        newsTitle:"",
        publishName: "",
        articleType: "",

        userTypeScope: "",
        publishUserTypeScope: publishUserTypeScope,
        newsTag:"",
        newsTagList:[],

        range: "",
        rangeList: [],
        rangeListLoaded: false,

        content: '', // 文章内容
        editorOption: {
          placeholder: '请输入内容',
          modules: { // 配置富文本
            toolbar: [
              ['bold', 'italic', 'underline', 'strike'],
              ['blockquote', 'code-block'],
              [{ 'header': 1 }, { 'header': 2 }],
              [{ 'direction': 'rtl' }],
              [{ 'size': ['small', false, 'large', 'huge'] }],
              [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
              [{ 'color': [] }, { 'background': [] }],
              [{ 'font': [] }],
              [{ 'align': [] }],
              ['clean'],
              ['link', 'image']
            ]
          }
        },
        addRange: [],
        //uploadData: {},
        photoUrl: '', // 上传图片地址
        uploadType: '' // 上传的文件类型（图片、视频）
      }
    },
    computed: {
      qnLocation () {
        return QINIU_UP_API;//编辑器图片上传地址
      }
    },
    components: {
      quillEditor  
    },
    created(){
      this.id = this.$route.query.id;
      this.type = this.$route.query.type;

      if (this.type=='add') {

      } else if (this.type == 'update') {
        this.fetchDetail();
      } else if (this.type == 'info') {
        this.fetchDetail();
      }
      //上传图片之前拉取的token 
      let vm=this;
      getQNToken().then(response => {
        let res=response.data.up_token;
        vm.postData.token=res;
      }).catch(error => {
        // console.log("失败")
      })
      
    },
    mounted () {
      // 为图片ICON绑定事件 getModule 为编辑器的内部属性
      this.$refs.myQuillEditor.quill.getModule('toolbar').addHandler('image', this.imgHandler)
    },
    methods:{
      fetchAreaList() {
        let vm = this;
        
        let params = {
          ril: 'S',
          page_num: 1,
          page_size: 999
        };
        getAreaList(params)
        .then(response => {
          vm.rangeList = response.data.rows;
          // console.log(vm.rangeList);
        })
        .catch(error => {

        })
      },
      fetchDetail() {
        let vm = this;
        getArticleDetail(vm.id)
        .then(response => {
          let res = response.data;
          vm.newsTitle = res.title;
          vm.newsDigest = res.digest;
          vm.time = res.send_time;
          vm.newsStatus = res.status;
          vm.publishName = res.publish_name;
          vm.thumbnailUrl = res.thumbnail;
          vm.content = res.content;
          vm.extraUrl = res.extraUrl;
          vm.articleType = res.type;
          vm.userTypeScope = res.to_user_type[0] + '';

          // 每个端都有不同的标签
          if (res.to_user_type[0] == 1) {
            vm.rangeList = res.area_infos;
            vm.range = res.area_infos[0].value;
          } 

          vm.newsTag = res.tags;
        })
        .catch(error => {

        })
      },
      genParam() {

        let param = {
          title: this.newsTitle,
          digest: this.newsDigest,
          send_time: this.time,
          status: this.newsStatus,
          tags: this.newsTag,
          type: this.articleType,
          thumbnail: this.thumbnailUrl,
          content: this.content,
          url: this.extraUrl,
          to_user_type: [],
          publish_name: this.publishName
        };
        param.to_user_type[0] = this.userTypeScope;

        if (this.userTypeScope == 1) {
          param.area_ids = [];
          param.area_ids[0] = this.range;
        }
        return param;
      },
      create(){//添加
        let vm = this;
        addArticle(this.genParam())
        .then(response => {
          vm.back();
        })
        .catch(error => {

        })
      },
      back(){//返回
        let vm=this;
        window.localStorage.setItem('pageNum',vm.$route.query.pageNum||1);
        vm.$router.go(-1);
      },
      modify:function(){
        let vm = this;
        let param = this.genParam();

        modifyArticle(this.id, param)
        .then(response => {
          vm.back();
        })
        .catch(error=> {
        });
      },
      clickUserTypeScopeChange() {
        if (this.userTypeScope == 1) {
          this.fetchAreaList();
        } else {
          this.range = "";
          this.rangeList = [];
        }

      },
      clickRange() {
        if (!this.rangeListLoaded) {
          this.fetchAreaList();
          this.rangeListLoaded = true;
        }
      },
      getArticleTypeTip() {
        return this.articleType == '2' ? '通知' : '公告';
      },
      handleAvatarSuccess(res, file) {
        this.imageUrl = URL.createObjectURL(file.raw);
        this.saveImageUrl=res.saveUrl;
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isJPG) {
          this.$message.error('上传的广告图只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传的广告图大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      },
      onEditorChange({ editor, html, text }) {
        this.content = html ;
      },
      onPreview(){//预览
        this.onPreviewDialog=true;
      },
      onOpen(){
        let vm=this;
        let iframeData=`
          <html>
            <head>
              <title>通知公告预览</title>
              <meta name="viewport" content="width=device-width,height=device-height,initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
              <style type="text/css">
                *{
                  padding: 0;
                  margin: 0;
                  font-size: 14px;
                  font-family: "Microsoft YaHei";
                  letter-spacing:1px;
                }
                a{
                  text-decoration: none;
                }
                img{
                  border:none;
                }
                .myContainer{
                  padding:15px;
                }
                .myHeader{
                  border-bottom:1px solid #d8d8d8;
                }
                .myTitleText{
                  font-weight: 600;
                  font-size: 16px;
                  color: #404040;
                  display: -webkit-box;
                    -webkit-box-orient: vertical;
                    -webkit-line-clamp: 2;
                    overflow: hidden;
                }
                .mySubtitle{
                  padding: 15px 0;
                }
                .myTime{
                  color: #959595;
                }
                .myBriefing{
                  float: right;
                  border:1px solid #72b2fe;
                  color: #72b2fe;
                  padding: 2px 5px;
                  border-radius: 10px;
                }
                .myContent{
                  padding: 15px 0;
                  color: #676566;
                  line-height: 1.7;
                  text-align: justify;
                  white-space:pre-wrap;
                }
                .myContent img{
                  width: auto;
                  max-width: 100%;
                  height: auto;
                  margin: 15px 0;
                }
                .ql-align-right{
                  text-align:right;
                }
                .ql-align-center{
                  text-align:center;
                }
                @media screen and (min-width: 720px) {
                  .myContainer{
                    width: 720px;
                    position: absolute;
                    left: 50%;
                    margin-left: -360px;
                  }
                }
                ::-webkit-scrollbar{
                  width:0;
                  height:0;
                }
              </style>
            </head>
            <body>
              <div class="myContainer">
                <div class="myHeader">
                  <p class="myTitleText">
                    ${vm.newsTitle}
                  </p>
                  <div class="mySubtitle">
                    <span class="myTime">
                      ${vm.time}
                    </span>
                    <a href="javascript:;" class="myBriefing">
                      ${vm.getArticleTypeTip()}
                    </a>
                  </div>
                </div>
                <div class="myContent">
                  ${vm.content}
                </div>
              </div>
            </body>
          </html>
        `
        window.setTimeout(function(){
          let myIframe=document.getElementById("myIframe");
          myIframe.contentWindow.document.head.innerHTML=''
          myIframe.contentWindow.document.body.innerHTML=''
          myIframe.contentWindow.document.write(iframeData);
        },100);        
      },
       // 这个钩子还支持 promise
      beforeUpload (file) {
        
      },
      // 图片上传成功回调 插入到编辑器中
      upScuccess (e, file, fileList) {
        let objE=e;
        this.fullscreenLoading = false
        let vm = this
        let url = ''
        // 获得文件上传后的URL地址
        url = QINIU_API + objE.key;
        if (url != null && url.length > 0) { // 将文件上传后的URL地址插入到编辑器文本中
          let value = url;
          vm.addRange = vm.$refs.myQuillEditor.quill.getSelection();
          value = value.indexOf('http') !== -1 ? value : 'http:' + value;
          vm.$refs.myQuillEditor.quill.insertEmbed(vm.addRange !== null ? vm.addRange.index : 0, vm.uploadType, value, Quill.sources.USER) // 调用编辑器的 insertEmbed 方法，插入URL
        } else {
          this.$message.error(`${vm.uploadType}插入失败`)
        }
        this.$refs['upload'].clearFiles() // 插入成功后清除input的内容
      },
      // 点击图片ICON触发事件
      imgHandler (state) {
        this.addRange = this.$refs.myQuillEditor.quill.getSelection();
        if (state) {
          let fileInput = document.getElementById('imgInput');
          fileInput.click(); // 加一个触发事件
        }
        this.uploadType = 'image';
      },
    }
  
  }


</script>




